package cn.sygenghan.android.zxing_lite;

import android.Manifest;
import android.content.Intent;
import android.content.pm.PackageManager;
import android.graphics.Bitmap;
import android.graphics.BitmapFactory;
import android.os.Build;
import android.support.v4.app.ActivityCompat;
import android.support.v4.content.ContextCompat;
import android.support.v7.app.AppCompatActivity;
import android.os.Bundle;
import android.view.View;
import android.widget.Button;
import android.widget.CheckBox;
import android.widget.EditText;
import android.widget.ImageView;
import android.widget.TextView;
import android.widget.Toast;

import cn.sygenghan.android.zxing.library.activity.CaptureActivity;
import cn.sygenghan.android.zxing.library.encode.QRCodeEncoder;

public class MainActivity extends AppCompatActivity implements View.OnClickListener {
    private TextView resultTextView;
    private EditText qrStrEditText;
    private ImageView qrImgImageView;
    private CheckBox checkBox;

    @Override
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.activity_main);

        resultTextView = findViewById(R.id.tv_scan_result);
        qrStrEditText = findViewById(R.id.et_qr_string);
        qrImgImageView = findViewById(R.id.iv_qr_image);
        checkBox = findViewById(R.id.logo);
        Button scanBarCodeButton = findViewById(R.id.btn_scan_barcode);
        scanBarCodeButton.setOnClickListener(this);
        Button generateQRCodeButton = findViewById(R.id.btn_add_qrcode);
        generateQRCodeButton.setOnClickListener(this);
    }

    @Override
    public void onClick(View view) {
        switch (view.getId()){
            case R.id.btn_scan_barcode:
                if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.M){
                    //判断是否已经赋予权限
                    if (ContextCompat.checkSelfPermission(this, Manifest.permission.CAMERA) != PackageManager.PERMISSION_GRANTED) {
                        //如果应用之前请求过此权限但用户拒绝了请求，此方法将返回 true。
                        if (ActivityCompat.shouldShowRequestPermissionRationale(this, Manifest.permission.CAMERA)) {
                            //这里可以写个对话框之类的项向用户解释为什么要申请权限，并在对话框的确认键后续再次申请权限
                            //
                            ActivityCompat.requestPermissions(this, new String[] { Manifest.permission.CAMERA }, 1);
                        } else {
                            //申请权限，字符串数组内是一个或多个要申请的权限，1是申请权限结果的返回参数，在onRequestPermissionsResult可以得知申请结果
                            ActivityCompat.requestPermissions(this, new String[] { Manifest.permission.CAMERA }, 1);
                        }
                    }
                    else {
                        startActivityForResult(new Intent(MainActivity.this, CaptureActivity.class), 0);
                    }
                }
                else {
                    //打开扫描界面扫描条形码或二维码
                    startActivityForResult(new Intent(MainActivity.this, CaptureActivity.class), 0);
                }
                break;
            case R.id.btn_add_qrcode:
                String contentString = qrStrEditText.getText().toString();
                if (!contentString.equals("")) {
                    //根据字符串生成二维码图片并显示在界面上，第二个参数为图片的大小（350*350）
                    Bitmap qrCodeBitmap = QRCodeEncoder.createQRCode(contentString, 350, 350,
                            checkBox.isChecked() ?
                                    BitmapFactory.decodeResource(getResources(), R.mipmap.launcher_icon) :
                                    null);
                    qrImgImageView.setImageBitmap(qrCodeBitmap);
                } else {
                    Toast.makeText(MainActivity.this, "Text can not be empty", Toast.LENGTH_SHORT).show();
                }
                break;
        }
    }

    @Override
    protected void onActivityResult(int requestCode, int resultCode, Intent data) {
        super.onActivityResult(requestCode, resultCode, data);
        if (resultCode == RESULT_OK) {
            Bundle bundle = data.getExtras();
            String scanResult = bundle.getString("result");
            resultTextView.setText(scanResult);
        }
    }

    @Override
    public void onRequestPermissionsResult(int requestCode, String[] permissions, int[] grantResults) {
        super.onRequestPermissionsResult(requestCode, permissions, grantResults);
        if (requestCode == 1) {
            for (int i = 0; i < permissions.length; i++) {
                if (grantResults[i] != PackageManager.PERMISSION_GRANTED) {
                    Toast.makeText(this, "" + "权限 " + permissions[i] + " 申请失败", Toast.LENGTH_SHORT).show();
                }
            }
        }
    }
}
